package com.huitong.gateway.filter;

import com.huitong.gateway.utils.WebFluxUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 缓存body请求数据过滤器 解决流不能重复读取问题
 *
 * @author fromdrowning
 * @date 2024/3/17 22:20
 */
@Component
public class CacheRequestFilter implements GlobalFilter, Ordered {

    /**
     * 缓存请求数据
     *
     * @param exchange 当前请求和响应的信息
     * @param chain    过滤器链
     * @return 响应式对象
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 只缓存json类型请求
        if (!WebFluxUtils.isJsonRequest(exchange)) {
            return chain.filter(exchange);
        }

        return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> {
            if (serverHttpRequest == exchange.getRequest()) {
                return chain.filter(exchange);
            }

            return chain.filter(exchange.mutate()
                .request(serverHttpRequest)
                .build());
        });
    }

    /**
     * 设置优先级
     *
     * @return 优先级
     */
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 1;
    }
}
